#!/bin/bash

# XY User System 轻量级部署脚本 (适用于2核2GB内存服务器)
# 使用方法: ./deploy-light.sh [操作]
# 操作: deploy, update, stop, restart, logs, status

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置
APP_NAME="xyuser-system-light"
DOCKER_COMPOSE_FILE="docker-compose.light.yml"
BACKUP_DIR="./backups"

# 函数定义
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查系统资源
check_system_resources() {
    log_info "检查系统资源..."
    
    # 检查内存
    TOTAL_MEM=$(free -m | awk 'NR==2{printf "%.0f", $2}')
    if [ "$TOTAL_MEM" -lt 1800 ]; then
        log_error "系统内存不足2GB，当前: ${TOTAL_MEM}MB"
        exit 1
    fi
    
    # 检查磁盘空间
    DISK_USAGE=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
    if [ "$DISK_USAGE" -gt 80 ]; then
        log_warning "磁盘使用率较高: ${DISK_USAGE}%"
    fi
    
    log_success "系统资源检查完成 - 内存: ${TOTAL_MEM}MB, 磁盘使用: ${DISK_USAGE}%"
}

# 优化系统设置
optimize_system() {
    log_info "优化系统设置..."
    
    # 设置swap（如果没有）
    if [ ! -f /swapfile ]; then
        log_info "创建1GB swap文件..."
        sudo fallocate -l 1G /swapfile
        sudo chmod 600 /swapfile
        sudo mkswap /swapfile
        sudo swapon /swapfile
        echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
    fi
    
    # 优化内核参数
    echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
    echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
    sudo sysctl -p
    
    log_success "系统优化完成"
}

# 检查Docker和Docker Compose
check_dependencies() {
    log_info "检查依赖..."
    
    if ! command -v docker &> /dev/null; then
        log_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi
    
    log_success "依赖检查完成"
}

# 清理Docker资源
cleanup_docker() {
    log_info "清理Docker资源以释放内存..."
    docker system prune -f
    docker volume prune -f
    docker image prune -f
    log_success "Docker资源清理完成"
}

# 创建必要的目录
create_directories() {
    log_info "创建必要的目录..."
    mkdir -p $BACKUP_DIR
    mkdir -p ./public/uploads
    log_success "目录创建完成"
}

# 备份数据库
backup_database() {
    log_info "备份数据库..."
    
    if docker-compose -f $DOCKER_COMPOSE_FILE ps mysql | grep -q "Up"; then
        BACKUP_FILE="$BACKUP_DIR/mysql_backup_$(date +%Y%m%d_%H%M%S).sql"
        docker-compose -f $DOCKER_COMPOSE_FILE exec -T mysql mysqldump -u xyuser -pyour_secure_password_here xyuser_db > "$BACKUP_FILE"
        log_success "数据库备份完成: $BACKUP_FILE"
    else
        log_warning "MySQL 容器未运行，跳过备份"
    fi
}

# 轻量级部署
deploy() {
    log_info "开始轻量级部署 $APP_NAME..."
    
    check_dependencies
    check_system_resources
    optimize_system
    cleanup_docker
    create_directories
    
    # 检查配置文件
    if [ ! -f ".env.production" ]; then
        log_warning ".env.production 文件不存在，请先配置环境变量"
    fi
    
    # 构建并启动服务
    log_info "构建并启动轻量级服务..."
    docker-compose -f $DOCKER_COMPOSE_FILE build --no-cache
    docker-compose -f $DOCKER_COMPOSE_FILE up -d
    
    # 等待服务启动
    log_info "等待服务启动..."
    sleep 45
    
    # 检查服务状态
    check_health
    
    log_success "轻量级部署完成！"
    show_status
    show_resource_usage
}

# 更新应用
update() {
    log_info "更新 $APP_NAME..."
    
    backup_database
    cleanup_docker
    
    # 拉取最新代码（如果使用Git）
    if [ -d ".git" ]; then
        log_info "拉取最新代码..."
        git pull origin master
    fi
    
    # 重新构建并重启
    log_info "重新构建应用..."
    docker-compose -f $DOCKER_COMPOSE_FILE build --no-cache app
    docker-compose -f $DOCKER_COMPOSE_FILE up -d app
    
    # 等待服务启动
    sleep 30
    check_health
    
    log_success "更新完成！"
    show_resource_usage
}

# 停止服务
stop() {
    log_info "停止 $APP_NAME..."
    backup_database
    docker-compose -f $DOCKER_COMPOSE_FILE down
    log_success "服务已停止"
}

# 重启服务
restart() {
    log_info "重启 $APP_NAME..."
    docker-compose -f $DOCKER_COMPOSE_FILE restart
    sleep 30
    check_health
    log_success "服务已重启"
    show_resource_usage
}

# 查看日志
show_logs() {
    log_info "显示应用日志..."
    docker-compose -f $DOCKER_COMPOSE_FILE logs -f --tail=50 app
}

# 检查服务健康状态
check_health() {
    log_info "检查服务健康状态..."
    
    # 检查容器状态
    if docker-compose -f $DOCKER_COMPOSE_FILE ps | grep -q "Up"; then
        log_success "容器运行正常"
    else
        log_error "部分容器未正常运行"
        docker-compose -f $DOCKER_COMPOSE_FILE ps
        return 1
    fi
    
    # 检查应用健康
    for i in {1..15}; do
        if wget --spider --quiet http://localhost:3000/health 2>/dev/null; then
            log_success "应用健康检查通过"
            return 0
        fi
        log_info "等待应用启动... ($i/15)"
        sleep 5
    done
    
    log_error "应用健康检查失败"
    return 1
}

# 显示服务状态
show_status() {
    log_info "服务状态:"
    docker-compose -f $DOCKER_COMPOSE_FILE ps
    
    echo ""
    log_info "访问地址:"
    echo "  - 应用:  http://localhost:3000"
    echo "  - 数据库: localhost:3306"
}

# 显示资源使用情况
show_resource_usage() {
    log_info "系统资源使用情况:"
    
    # 内存使用
    echo "内存使用:"
    free -h
    
    echo ""
    echo "Docker容器资源使用:"
    docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}"
    
    echo ""
    echo "磁盘使用:"
    df -h /
}

# 监控资源使用
monitor() {
    log_info "实时监控资源使用情况 (按Ctrl+C退出)..."
    while true; do
        clear
        echo "=== XY User System 资源监控 ==="
        echo "时间: $(date)"
        echo ""
        
        echo "内存使用:"
        free -h
        echo ""
        
        echo "Docker容器状态:"
        docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}"
        echo ""
        
        echo "磁盘使用:"
        df -h / | tail -1
        echo ""
        
        echo "负载平均值:"
        uptime
        
        sleep 5
    done
}

# 主函数
main() {
    local action=${1:-deploy}
    
    case $action in
        "deploy")
            deploy
            ;;
        "update")
            update
            ;;
        "stop")
            stop
            ;;
        "restart")
            restart
            ;;
        "logs")
            show_logs
            ;;
        "status")
            show_status
            ;;
        "health")
            check_health
            ;;
        "cleanup")
            cleanup_docker
            ;;
        "backup")
            backup_database
            ;;
        "monitor")
            monitor
            ;;
        "resources")
            show_resource_usage
            ;;
        "optimize")
            optimize_system
            ;;
        *)
            echo "使用方法: $0 [deploy|update|stop|restart|logs|status|health|cleanup|backup|monitor|resources|optimize]"
            echo ""
            echo "命令说明:"
            echo "  deploy    - 轻量级部署应用"
            echo "  update    - 更新应用"
            echo "  stop      - 停止所有服务"
            echo "  restart   - 重启所有服务"
            echo "  logs      - 查看应用日志"
            echo "  status    - 查看服务状态"
            echo "  health    - 检查服务健康状态"
            echo "  cleanup   - 清理Docker资源"
            echo "  backup    - 备份数据库"
            echo "  monitor   - 实时监控资源使用"
            echo "  resources - 显示资源使用情况"
            echo "  optimize  - 优化系统设置"
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"